import oss2 
import json
from aliyunsdkcore import client
from aliyunsdkcore.profile import region_provider
from aliyunsdksts.request.v20150401 import AssumeRoleRequest

ak = "LTAI5tFrXVW9qNuE249cnKrD"
sk="EpjT0VisSbZR3MkI7882DaYKyh5RM0"
sts_role_arn = 'acs:ram::1424666767642849:role/oss2upload'
# 在控制台将 AliyunSTSAssumeRoleAccess 权限授权给子用户testRole，testRole操作AssumeRole接口，获取临时身份
def fetch_sts_info(access_key_id, access_key_secret, sts_role_arn):
    """子用户角色扮演获取临时身份的信息
    :param access_key_id: 子用户的 access key id
    :param access_key_secret: 子用户的 access key secret
    :param sts_role_arn: STS角色的Arn
    :return StsInfo 返回临时身份信息对象
    """
    # 配置要访问的STS endpoint
    REGIONID = 'cn-beijing'
    ENDPOINT = 'sts.cn-beijing.aliyuncs.com'
    region_provider.add_endpoint('Sts', REGIONID, ENDPOINT)

    clt = client.AcsClient(access_key_id, access_key_secret, 'cn-beijing')
    request = AssumeRoleRequest.AssumeRoleRequest()

    #request.set_accept_format('json')
    #指定角色ARN
    request.set_RoleArn(sts_role_arn)
    #设置会话名称，审计服务使用此名称区分调用者
    request.set_RoleSessionName('hhuc-oss-upload')
    request.set_DurationSeconds(1200)
    #发起请求，并得到response
    response = clt.do_action_with_exception(request)
    #格式化输出返回结果，将字符串结果转化为字典类型
    i = json.loads(oss2.to_unicode(response))
    #实例化StsInfo类，并将通过sts获取的临时身份信息存入
    '''
    global StsInfo
    StsInfo = StsInfo()
    StsInfo.access_key_id = i['Credentials']['AccessKeyId']
    StsInfo.access_key_secret = i['Credentials']['AccessKeySecret']
    StsInfo.security_token = i['Credentials']['SecurityToken']
    StsInfo.request_id = i['RequestId']
    StsInfo.expiration = oss2.utils.to_unixtime(i['Credentials']['Expiration'], '%Y-%m-%dT%H:%M:%SZ')
    '''
    #返回StsInfo对象
    return i

a = fetch_sts_info(ak, sk ,  sts_role_arn)
print(a)
